package com.syni.mdd.yhd.common.all.quartz.video;

import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.entity.BmsBusiness;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrder;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrderStatus;
import com.syni.mdd.yhd.common.all.entity.BmsVideo;
import com.syni.mdd.yhd.common.all.quartz.order.job.OrderCancelTimingJob;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.VideoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @className BmsVideoQuartz
 * @description TOO
 * @Author cfx
 * @DATE 2019/7/26 16:15
 * @VERSION 1.0
 **/
@Component
@EnableScheduling
public class BmsVideoQuartz {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    BmsUserOperationLogService bmsUserOperationLogService;

    @Autowired
    BmsVideoService bmsVideoService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Scheduled(cron = "0 0 0 * * ?")  //每天晚上凌晨执行一次定时任务
    public void resetVideoNoRandom() {
        VideoUtils.getBusinessRandom().clear();
        VideoUtils.getUserRandom().clear();
        log.info("...清楚完毕.....");
        log.info("userRandom：" + VideoUtils.getUserRandom().size());
        log.info("businessRandom：" + VideoUtils.getBusinessRandom().size());
    }

    /**
     * @Description 统计视频的播放量
     * @Author: cfx
     * @Date: 2019/8/15
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void countVideoPlayNum() {
        log.info("..............count videoPlayNum start.............");
        Date endTime = new Date();
        Date startTime = DateTimeUtils.addHour(endTime,-2);
        final int userOperationType = 12;
        String startTimes = DateTimeUtils.converDateToString(startTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        String endTimes = DateTimeUtils.converDateToString(endTime,DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        List<Map<String,Object>> bmsUserOperationLogs = bmsUserOperationLogService.getBaseDao().countVideoPlayNum(userOperationType,
                startTimes,endTimes);
        if(bmsUserOperationLogs.size() > 0){
            Set<Integer> videoIds = new HashSet<>();
            for(Map<String,Object> userOperationMap : bmsUserOperationLogs){
                if(userOperationMap.containsKey("video_id") && StringUtils.checkNullAndEmpty(userOperationMap.get("video_id"))){
                    videoIds.add(Integer.parseInt(userOperationMap.get("video_id").toString()));
                }
            }
            Map<Integer,BmsVideo> bmsVideoMap = new HashMap<>();
            if(videoIds.size() > 0){
                bmsVideoMap = bmsVideoService.findByIdIn(videoIds);
            }
            List<BmsVideo> bmsVideos = new LinkedList<>();
            for(Map<String,Object> userOperationMap : bmsUserOperationLogs){
                Integer videoId = Integer.parseInt(userOperationMap.get("video_id").toString());
                Integer num = Integer.parseInt(userOperationMap.get("num").toString());
                if(bmsVideoMap.containsKey(videoId)){
                    BmsVideo bmsVideo = bmsVideoMap.get(videoId);
                    bmsVideo.setPlayNum(bmsVideo.getPlayNum() == null ? num : bmsVideo.getPlayNum() + num);
                    bmsVideos.add(bmsVideo);
                }
            }
            if(bmsVideos.size() > 0){
                bmsVideoService.getBaseDao().saveAll(bmsVideos);
            }
        }
    }

    /**
     * @Description 统计视频的播放量,点赞量，销售量
     * @Author: cfx
     * @Date: 2019/8/15
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void countVideoStatic() {
        log.info("..............count videoStatic start.............");
        //分页获取
        Integer pageNum = 1;
        Integer pageSize = 100;
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete", Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("isRelease",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("isOff",Constants.COMMON_FLAG_FALSE_INT);
        while (true) {
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize);
            List<BmsVideo> bmsVideos = bmsVideoService.getBaseDao().findAll(new SpecificationUtils(conditionMap),pageable).getContent();
            if(bmsVideos != null && bmsVideos.size() > 0){
                for(BmsVideo bmsVideo : bmsVideos){
                    List<Integer> staticData = new LinkedList<>();
                    Integer likeTimes = bmsVideo.getLikeTimes() == null ? 0 : bmsVideo.getLikeTimes();
                    Integer commentNum = bmsVideo.getCommentNum() == null ? 0 : bmsVideo.getCommentNum();
                    Integer playNum = bmsVideo.getPlayNum() == null ? 0 : bmsVideo.getPlayNum();
                    staticData.add(likeTimes);
                    staticData.add(commentNum);
                    staticData.add(playNum);
                    redisTemplate.opsForList().rightPush(Constants.REDIS_KEY_VIDEO_STATIC + bmsVideo.getId(),staticData);
                }
                pageNum++;
            }else {
                break;
            }
        }
    }

    @Scheduled(cron = "0 0 12 * * ?")  //每天晚上凌晨执行一次定时任务
    //@Scheduled(cron = "0/5 * * * * ?")
    public void clearUploadBusinessVideo() {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isUnload",Constants.COMMON_FLAG_TRUE_INT);
        List<BmsBusiness> bmsBusinesses = bmsBusinessService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        if(bmsBusinesses != null && bmsBusinesses.size() > 0){
            Set<Integer> businessIds = bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet());
            if(businessIds.size() > 0){
                bmsVideoService.AdjustVideoRating(businessIds);
                bmsDxGroupBuyService.uploadBmsDxGroupBuy(businessIds);
            }
        }
    }
}
